﻿using RBACProject.Application.Permission.Dto;
using RBACProject.Domian;
using RBACProject.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RBACProject.Application.Permission
{
    public class PermissionService: IPermissionService
    {

        /// <summary>
        /// 获取属性
        /// </summary>
        private readonly IBaseRepository<RoleMenuModel> Rolemenu;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="rolemenu"></param>
        public PermissionService(IBaseRepository<RoleMenuModel> rolemenu)
        {
            Rolemenu = rolemenu;
        }
        

        /// <summary>
        /// 反填角色权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultDto<List<int>>> GetMenuId(int id)
        {
            List<int> ids = new List<int>();
            var data = await Rolemenu.QueryWhere(x => x.RoleId == id);
            foreach (var item in data)
            {
                ids.Add(item.MenuId);
            }
            return new ResultDto<List<int>>
            {
                Data = ids,
                Result = Result.Success
            };
        }


        /// <summary>
        ///  角色权限分配(修改)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDto> EditAssignPermission(PermissonDto dto)
        {
            var list = await Rolemenu.DeleteAsyncWhere(x => x.RoleId == dto.RoleId);
            var data = dto.PermissonIds.Select(x => new RoleMenuModel
            { 
                MenuId = x,     //菜单Id
                RoleId= dto.RoleId,   //角色Id
            }).ToList();
            await Rolemenu.InsertManyAsync(data);
            return new ResultDto 
            { 
                Result = Result.Success,
                Message= "权限分配成功！",
            };
        }
    }
}
